package com.huanxing.cloud.upms.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;
import com.huanxing.cloud.common.core.constant.CacheConstants;
import com.huanxing.cloud.common.core.util.Result;
import com.huanxing.cloud.common.log.annotation.SysLog;
import com.huanxing.cloud.upms.api.entity.SysUserOnline;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 系统在线用户
 *
 * @author lijx
 * @since 2022/2/26 16:45
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/onlineuser")
@Tag(description = "onlineuser", name = "系统在线用户")
public class SysOnlineUserController {

	private final StringRedisTemplate redisTemplate;

	@Operation(summary = "在线用户列表")
	@GetMapping("/list")
	public Result<List<SysUserOnline>> page() {
		Set<String> keys = redisTemplate.keys(CacheConstants.SYS_ONLINE_KEY + "*");
		if (CollectionUtils.isEmpty(keys)) {
			return Result.success(null);
		}

		List<SysUserOnline> sysUserOnlines = redisTemplate.opsForValue().multiGet(keys).stream().map(obj -> {
			return JSONUtil.toBean(obj, SysUserOnline.class);
		}).sorted((u1, u2) -> u2.getLoginTime().compareTo(u1.getLoginTime())).collect(Collectors.toList());
		return Result.success(sysUserOnlines);
	}

	@SysLog("强退用户")
	@Operation(summary = "强退用户")
	@DeleteMapping("/{token}")
	public Result<Void> kickoutByToken(@PathVariable String token) {
		StpUtil.kickoutByTokenValue(token);
		return Result.success();
	}

}
